<template>
  <div class="fee-box">
    <div class="fee-content">
      <details-head :title="`费用详情`"
                    :multiple="true"
                    :show-print="true"
                    print-router="WaybillFeePrint"
                    :print-query="{
                      waybillId: waybillId,
                      status: isStatus
                    }" />
      <div class="pad20">
        <el-row :gutter="40"
                class="des-wrap">
          <el-col class="wrap-left"
                  :span="8">
            <div class="text-center f18">
              <b v-if="wayDetails.fromAddress">
                {{ wayDetails.fromAddress.city === '市辖区' ? wayDetails.fromAddress.province : wayDetails.fromAddress.city }}
              </b>
              <icon-svg class="font-style"
                        class-name="iconClass"
                        icon-name="jiantou" />
              <b v-if="wayDetails.toAddress">
                {{ wayDetails.toAddress.city === '市辖区'? wayDetails.toAddress.province : wayDetails.toAddress.city }} </b>
            </div>
            <quote-list :info="quoteData"
                        :config-data="configData"
                        :icon-name="iconName"
                        :content="content" />
          </el-col>
          <el-col :span="16">
            <el-row class="mb20">
              <el-col :span="12">
                <descriptions v-if="wayDetails.customer"
                              :info="
                Object.assign(
                  {},
                  wayDetails.customer,
                  wayDetails.fromAddress,
                  wayDetails.fromContact
                )
              "
                              type="sender"
                              :is-quote="true"
                              :from-time="wayDetails.fromTime"
                              :company="wayDetails.customer.showCustomerName" />
              </el-col>
              <el-col :span="12">
                <descriptions v-if="wayDetails.consignee"
                              :info="
                Object.assign(
                  {},
                  wayDetails.consignee,
                  wayDetails.toAddress,
                  wayDetails.toContact
                )
              "
                              type="consign"
                              :is-quote="true"
                              :to-time="wayDetails.toTime"
                              :company="wayDetails.consignee.consigneeName" />
              </el-col>
            </el-row>
            <total-list class="mb20"
                        base
                        :info="
            Object.assign(
              {},
              wayDetails.waybillCache,
              wayDetails.transportRequirement
            )
          "
                        :config-data="totalData" />
            <simple-list :info="
            Object.assign(wayDetails.transportRequirement || {}, {
              orderDesc: wayDetails.desc,
              calculateValue: waybillCaches.calculateValue ? formatNumber(waybillCaches.calculateValue) : 0
            })
          "
                         :config-data="transportQuoteInfoArr" />
          </el-col>
        </el-row>
        <layer v-if="abnormal"
               title="货物异常">
          <el-table :data="currentData"
                    stripe
                    max-height="450px"
                    style="width: 100%">
            <template v-for="(item, index) in goodsTableHeader">
              <el-table-column v-if="item.type === 'goodsName' || item.type === 'exceptionDesc'"
                               :key="index"
                               :prop="item.type"
                               :label="item.label"
                               :width="`${item.width}px`"
                               :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <div v-if="scope.row[item.type]">{{ scope.row[item.type] }}</div>
                  <div v-else>--</div>
                </template>
              </el-table-column>
              <el-table-column v-else
                               :key="index"
                               :prop="item.type"
                               :label="item.label"
                               :width="`${item.width}px`"
                               :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <div v-if="
                  (scope.row.goodsReceipt && scope.row.goodsReceipt[item.type]) ||
                  (scope.row.goodsSign && scope.row.goodsSign[item.type])
                ">
                    {{
                  (scope.row.goodsReceipt && scope.row.goodsReceipt[item.type]) ||
                  (scope.row.goodsSign && scope.row.goodsSign[item.type])
                }}
                  </div>
                  <div v-else>0</div>
                </template>
              </el-table-column>
            </template>
          </el-table>
          <el-pagination class="pagination"
                         :current-page="page"
                         :page-size="pageSize"
                         :total="total"
                         :page-sizes="[10, 20, 50, 100]"
                         layout="total, sizes, prev, pager, next, jumper"
                         @size-change="handleSizeChange"
                         @current-change="handleCurrentChange">
          </el-pagination>
        </layer>
      </div>
      <layer title="费用信息">
        <transport-quote v-if="wayBillColumn.length"
                         :data-list="priceList"
                         :combine-id="combineId"
                         :quotation-column="wayBillColumn" />
        <SurchargeFee v-if="!combineId"
                      :data-list="addCostList" />
        <div class="total-label">
          <div>
            已{{paymentLabel}}款: <b class="c-primary">{{ formatNumber(processedFee) }}</b>
            <el-tooltip placement="top"
                        effect="light">
              <div slot="content">已{{paymentLabel}}款：<br />
                初始为0.00元，财务将运单的（预付款、货到付款、代收货款、回执付款）进行{{paymentLabel}}款操作，已{{paymentLabel}}款将增加相应的金额</div>
              <icon-svg class-name="iconClass ml12"
                        icon-name="bangzhuzhongxin1" />
            </el-tooltip>
            <span class="ml100"></span>
            未{{paymentLabel}}款: <b class="c-primary">{{ formatNumber(pendingFee)  }}</b>
            <el-tooltip placement="top"
                        effect="light">
              <div slot="content">未{{paymentLabel}}款: <br />
                初始为已审核同意的运单费用，该费用从财务角度分为预付款、货到付款、代收货款、回执付款，财务将这四种款项进行{{paymentLabel}}款操作，未{{paymentLabel}}款将减去相应的金额</div>
              <icon-svg class-name="iconClass ml12"
                        icon-name="bangzhuzhongxin1" />
            </el-tooltip>
          </div>
          <!-- <div>
            报价费用+补充费用合计(含税费): <b class="c-primary">{{ totalFee || 0 }}</b>
          </div> -->
        </div>
        <pay-type disabled
                  :data-list="payList" />
      </layer>
      <layer title="其他信息">
        <el-row class="mb10">
          <el-col :span="2"> 备注 </el-col>
          <el-col :span="22"> {{ wayDetails.desc }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="2"> 附件 </el-col>
          <el-col :span="22">
            <upload-file-selector v-if="photo.length > 0"
                                  :is-onload="true"
                                  :is-create="true"
                                  :is-cover="true"
                                  :is-disabled="true"
                                  :attach-form.sync="photo" />
          </el-col>
        </el-row>
      </layer>
      <layer v-show="isTrack"
             title="跟踪信息">
        <Information :value="track" />
      </layer>
    </div>
  </div>
</template>

<script>
import Layer from "@/components/detailsLayer/Layer";
import DetailsHead from "@/components/detailsHead/Header";
import SimpleList from "@components/orderDetail/SimpleList.vue";
import QuoteList from "@/views/quote/transport/components/QuoteList.vue";
import Descriptions from "@views/quote/transport/components/Descriptions.vue";
import TotalList from "@/views/quote/transport/components/TotalList.vue";
import TransportQuote from "@/views/quote/transport/components/TransportQuote.vue";
import SurchargeFee from "@/views/quote/transport/components/SurchargeFee.vue";
import PayType from "@/views/quote/transport/components/PayType.vue";
import UploadFileSelector from "@/components/advance/upload/UploadFileSelector.vue";
import Information from "@/components/track/Information.vue";
import { quotation, transport, finance, track } from "@/api/index";
import { volumeOrWeightConversion } from "@/libs/util.js";
import {
  transportQuoteInfoArr, QuoteCstArr, QuoteCarrArr, totalData, quotationCostName
} from "@components/orderDetail/orderData";
import WaybillMixin from "@/components/waybill/waybill.mixin";

export default {
  name: "WayFeeDetail",
  components: {
    SimpleList,
    TotalList,
    Descriptions,
    QuoteList,
    Layer,
    PayType,
    SurchargeFee,
    TransportQuote,
    UploadFileSelector,
    Information,
    DetailsHead,
  },
  mixins: [WaybillMixin],
  data () {
    return {
      page: 1,
      pageSize: 10,
      total: 0,
      tableData: [], // 货物总数据
      currentData: [], //当前数据
      transportQuoteInfoArr,
      totalData, // 运单显示数据项
      abnormal: false, //货物异常标记
      combineId: null, //合单id
      goodsTableHeader: [
        { label: "物品名称", type: "goodsName", width: 330 },
        { label: "缺少", type: "lackQuantity", width: 200 },
        { label: "破损", type: "damageQuantity", width: 200 },
        { label: "丢失", type: "loseQuantity", width: 200 },
        { label: "其他", type: "otherQuantity", width: 200 },
        { label: "异常描述", type: "exceptionDesc", width: 520 }
      ],
      photo: [], //附件
      files: [],
      wayDetails: {}, //运单详情
      waybillCaches: {},
      quoteData: {},
      priceList: [], //报价费用
      addCostList: [], //补充费用
      payList: [], //预付费用
      // totalFee: 0, //总合计
      pendingFee: 0, //未收
      processedFee: 0, // 已收
      track: [], // 跟踪信息
      isTrack: false // 跟踪信息标题显示
    };
  },
  computed: {
    waybillId () {
      return this.$route.query.waybillId
    },
    waybillType () {
      return this.wayDetails?.waybillType;
    },
    configData () {
      return this.waybillType === 10 ? QuoteCstArr : QuoteCarrArr;
    },
    paymentLabel () {
      return this.waybillType === 10 ? '收' : '付';
    },
    isStatus () {
      return this.wayDetails?.status
    },
    formatNumber () {
      return num => num ? Number(num).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,') : 0;
    },
    content () {
      const { carrier, customer } = this.wayDetails
      // 承运方报价
      if (this.waybillType === 20) {
        if (carrier?.carrierType === 0) {
          return '线下'
        }
        if (carrier?.carrierType === 1 && carrier.carrierExtraType == 0) {
          return '线上'
        }
      } else {
        switch (customer?.showCustomerType) {
          case 0:
            return '线下';
          case 1:
            return '线上';
          default:
            return '';
        }
      }
      return '';
    },
    iconName () {
      const { carrier, customer } = this.wayDetails
      // 承运方报价
      if (this.waybillType === 20) {
        if (carrier?.carrierType === 0) {
          return 'xianxia'
        }
        if (carrier?.carrierType === 1 && carrier.carrierExtraType == 0) {
          return 'xianshang'
        }
      } else {
        switch (customer?.showCustomerType) {
          case 0:
            return 'xianxia';
          case 1:
            return 'xianshang';
          default:
            return '';
        }
      }
      return '';
    }
  },
  created () {
    this.getTransportDetail();
    this.getCollectionInfo();
    this.trackInformation();
  },
  methods: {
    //获取运单信息
    async getTransportDetail () {
      let { data } = await transport.getDetail(this.waybillId);
      this.getQuoteDetail();
      this.wayDetails = data;
      this.combineId = data?.combineId
      // 运单计费模式为重量 计费单位为吨
      if (
        data.transportRequirement?.chargeMode === 1 &&
        data.transportRequirement?.pricingUnit === 2
      ) {
        data.waybillCache.calculateWeight = volumeOrWeightConversion(
          0,
          data.waybillCache.calculateWeight
        );
      }
      // 运单计费模式为体积 计费单位为升
      if (
        data.transportRequirement?.chargeMode === 2 &&
        data.transportRequirement?.pricingUnit === 4
      ) {
        data.waybillCache.calculateVolume = volumeOrWeightConversion(
          1,
          data.waybillCache.calculateVolume
        );
      }
      let goodsData = [];
      data.goodsList.map((item) => {
        if (
          item?.goodsSign?.exceptionQuantity > 0 ||
          item?.goodsReceipt?.exceptionQuantity > 0
        ) {
          item.exceptionDesc = item.goodsReceipt ? item.goodsReceipt.exceptionDesc : item.goodsSign.exceptionDesc
          goodsData.push(item);
        }
      });
      this.tableData = goodsData;
      this.currentData = JSON.parse(JSON.stringify(this.tableData)).splice(
        0,
        this.pageSize
      );
      this.total = goodsData.length;
      this.abnormal =
        data?.sign?.exceptionQuantity > 0 ||
        data?.receipt?.exceptionQuantity > 0;
      if (data?.receipt?.exceptionQuantity === 0) {
        this.abnormal = false;
      }
      if (data.attachments) {
        this.photo = data.attachments.filter((x) => x.type === 2);
      }
      this.waybillCaches = data.waybillCache;
      this.quoteData = {
        contractNo: data.contractNo,
        createAt: data.createAt,
        orderNo: data.orderNo,
        createName: data.createBy.name,
        customerName: data.customer.showCustomerName,
        carrierName: data.carrier.carrierName,
        driverName: data.carrier.driverName
      };
    },
    // 获取收款信息
    async getCollectionInfo () {
      let { data } = await finance.getCollectionInfo(this.waybillId);
      this.pendingFee = data?.pendingFee
      this.processedFee = data?.processedFee
    },
    //获取报价详情
    async getQuoteDetail () {
      let { code, data } = await quotation.getValidWaybillQuotation(this.waybillId);
      if (code !== 0) return;
      if (data) {
        this.priceList = [
          {
            pick: data?.pickFee || 0, //提货费
            deliver: data?.deliverFee || 0, //送货费
            onLoad: data?.loadFee || 0, //装货费
            offLoad: data?.unloadFee || 0, //卸货费
            insure: data?.insureFee || 0, //保险费
            tax: data?.taxFee || 0, // 税费
            minCost: data?.minimumFee || 0, // 最低费用
            surchargeFee: data?.surchargeFee || 0, // 补充费用
            totalFee: data?.totalFee || 0
          }
        ];
        // transportMode 1零担 2整车
        if (this.wayDetails.transportRequirement.transportMode === 1) {
          this.priceList[0].less = data?.transportFee || 0;
        } else {
          this.priceList[0].full = data?.transportFee || 0;
        }
        // 补充费用
        this.addCostList = data?.surchargeFees || [];
        // 付款方式
        this.payList = [
          {
            arrivePayFee: data.arrivePayFee, //货到付款
            collectionFee: data.collectionFee, //代收货款
            prepayFee: data.prepayFee //预付款
          }
        ];
      }
    },
    // 分页数量改变
    handleSizeChange (value) {
      let arr = JSON.parse(JSON.stringify(this.tableData)).splice(0, value);
      this.currentData = [...arr];
      this.page = 1;
      this.pageSize = value;
    },
    // 当前页数改变
    handleCurrentChange (value) {
      let arr = JSON.parse(JSON.stringify(this.tableData)).splice(
        (value - 1) * this.pageSize,
        value * this.pageSize
      );
      this.currentData = [...arr];
      this.page = value;
    },
    // 返回
    back () {
      this.$router.back();
    },
    // 跟踪信息
    async trackInformation () {
      let type = 'bill'
      let { code, data } = await track.information(this.waybillId, type);
      if (code === 0 && data.length) {
        data.map(item => {
          if (item.message.indexOf('，') != -1 && item.message.lastIndexOf('】')) {
            item.timestamp = item.message.slice(0, item.message.indexOf('，'))
            item.date = item.message.slice(item.message.indexOf('，') + 1, item.message.lastIndexOf('】') + 1)
            item.content = item.message.slice(item.message.lastIndexOf('】') + 1)
          }
        })
        this.track = data
        this.isTrack = true
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.fee-box {
  width: 100%;
  height: calc(100vh);
  overflow-x: hidden;
  overflow-y: scroll;
}
.fee-content {
  width: 1200px;
  margin: 0 auto;
  background: var(--prev-bg-white);
}
.pad20 {
  padding: 20px;
}
.mb20 {
  margin-bottom: 20px;
}
.mb80 {
  margin-bottom: 80px;
}
.des-wrap {
  overflow: hidden;
  .wrap-left {
    position: relative;
    &:after {
      content: "";
      width: 1px;
      height: 2000px;
      background: #ebebeb;
      position: absolute;
      right: 10px;
      top: 0;
    }
  }
}
.font-style {
  font-size: 36px;
  margin: 0 10px;
  position: relative;
  top: 5px;
}
.total-label {
  color: var(--prev-color-text-ashes);
  display: flex;
  justify-content: space-between;
  height: 40px;
  line-height: 40px;
  margin: 20px 0;
}
.pagination {
  display: flex;
  justify-content: flex-end;
  height: 50px;
  margin-top: 10px;
}
.ml12 {
  margin-left: 12px;
}
.ml100 {
  margin-left: 100px;
}
</style>
